# -*- coding: utf-8 -*-
# @Time    : 2020/3/16 10:38
# @Author  : Sunny
# @Site    : 
# @File    : account.py
# @Software: PyCharm
# @WeChat public address : 程序猿与python之间的秘密
from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import UserModelForm, SendSmsForm, loginSmsForm, LoginForm
from django.http import JsonResponse
from web.models import User
from util.image_code import check_code
from io import BytesIO
from django.db.models import Q


# 用户注册，短信，登陆，注销


def register(request):
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, "register.html", {'form': form})
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_code(request):
    send_sms_form = SendSmsForm(request, data=request.GET)
    if send_sms_form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': send_sms_form.errors})


def login_sms(request):
    if request.method == 'GET':
        form = loginSmsForm()
        return render(request, 'login_sms.html', {'form': form})
    form = loginSmsForm(data=request.POST)
    if form.is_valid():
        phone = form.cleaned_data['phone']

        # 把用户名写入到session中
        user_object = User.objects.filter(phone=phone).first()

        request.session['user_id'] = user_object.id
        request.session['user_name'] = user_object.username

        return JsonResponse({"status": True, 'data': "/index/"})

    return JsonResponse({"status": False, 'error': form.errors})


def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = User.objects.filter(Q(email=username) | Q(phone=username)).filter(password=password).first()
        if user_obj:
            # 登陆成功
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """
    生成图片验证码
    @param request:
    @return:
    """
    img_obj, code = check_code()
    request.session['image_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间60s
    stream = BytesIO()
    img_obj.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    """
    注销
    @param request:
    @return:
    """
    request.session.flush()
    return redirect('index')
